import axios from 'axios'
import { setUser } from '../reducers/userReducer'

export const login = (apiKey, secretKey) => {
	return async dispatch => {
		try {
			const response = await axios.patch(
				'https://d43a-178-141-145-65.ngrok-free.app/api/user/login',
				{
					telegramID: window.Telegram.WebApp.initDataUnsafe.user.id,
					apiKey: apiKey,
					secretKey: secretKey,
				}
			)
			if (response.data) dispatch(setUser())
		} catch (err) {
			alert(err)
		}
	}
}

export const checkUser = () => {
	return async dispatch => {
		try {
			const response = await axios.post(
				'https://d43a-178-141-145-65.ngrok-free.app/api/user/auth',
				{
					id: window.Telegram.WebApp.initDataUnsafe.user.id,
				}
			)
			if (response.data) dispatch(setUser())
		} catch (e) {
			alert(e)
		}
	}
}
